package com.example.handsets8app.View;

import androidx.annotation.Nullable;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.handsets8app.Base.BaseActivity;
import com.example.handsets8app.Base.BaseConfig;
import com.example.handsets8app.Bean.JJHCheckResultBean;
import com.example.handsets8app.Bean.JJHCheckResultOtherBean;
import com.example.handsets8app.Bean.JJHCheckTicketBean;
import com.example.handsets8app.Bean.JJHCheckTicketOtherBean;
import com.example.handsets8app.Bean.JJHCheckTicketOtherSecondBean;
import com.example.handsets8app.Customer.CheckResultem;
import com.example.handsets8app.Customer.CheckTip;
import com.example.handsets8app.Customer.SecondConfigDialog;
import com.example.handsets8app.R;
import com.example.handsets8app.RetrufitHelp.BaseSubscriber;
import com.example.handsets8app.RetrufitHelp.ExceptionHandle;
import com.example.handsets8app.RetrufitHelp.RetrofitClient;
import com.example.handsets8app.Utils.IDCardUtils;
import com.example.handsets8app.Utils.LogUtil;
import com.example.handsets8app.Utils.SPUtil;
import com.example.handsets8app.Utils.StringUtil;
import com.example.handsets8app.Utils.TimeUtil;
import com.example.handsets8app.Utils.ToastUtil;

import com.example.handsets8app.Utils.util;
import com.synjones.handsetS8L.ScanDevice;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;
import com.synjones.reader.IDCardReaderModule;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class NewXinZhongXinActivity extends BaseActivity {
    private CheckTip checkTip;
    private LinearLayout llPrepare;
    private LinearLayout llCheckResult;
    private TextView tvLinkBroken;
    private TextView tvTime;
    private TextView tvCheckingID;
    private TextView checkCount;
    private RelativeLayout faceCheck;
    private RelativeLayout setting;
    private RelativeLayout qrCheck;
    private RelativeLayout HqrCheck;
    private RelativeLayout idCheck;
    private RelativeLayout idScanCheck;
    private RelativeLayout mCardCheck;
    private JJHCheckTicketBean jjhCheckTicketBean;
    private JJHCheckTicketOtherBean jjhCheckTicketOtherBean;

    private CheckResultem tickName;
    //    private CheckResultem tickNumber;
    private CheckResultem tickPersonNum;
    private CheckResultem tickPersonName;
    private CheckResultem tickTime;
    private CheckResultem tickMerction;
    private final int faceUp = 0;


    private static final int ReadScan = 0x11;

    //引入读取身份证，  新中心

    private boolean reading = false;
    public IDCardReaderModule idCardReaderModule;

    private String status = "";
    private static final int UpDateTime = 0x04;
    boolean boolReadFringerprint = false;
    private static final int ReadOnceDone = 0x01;
    private boolean isReadingID = false;
    private boolean isReadingCard = false;
    private long timeNew;
    private long timeOld;
    private String OldID;


    //语音的引入
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    private String gateSoundName;


    //寻找卡类型

    private static final int ReadThreadDone = 0x09;

    private Timer timer;
    private final int cardAgain = 201;


    private String barcodeStr;
    ScanDevice sm;
    //扫身份证的引入
    public static final int SCAN_IDCARD_REQUEST = 1;
    private final static String SCAN_ACTION = "scan.rcv.message";

    private JJHCheckTicketOtherSecondBean secondBean;
    private ReadCardThread ReadCardThreadhandler;

    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i("zyf", "onInit: TTS引擎初始化成功");
            } else {
                Log.i("zyf", "onInit: TTS引擎初始化失败");
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case faceUp:
                    tvTime.setText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3));
                    mHandler.sendEmptyMessageDelayed(faceUp, 10000);
                    break;
                case ReadScan:
                    String ScanNumber = (String) msg.obj;
                    if (!StringUtil.isNullOrEmpty(ScanNumber)) {

                        llPrepare.setVisibility(View.GONE);
                        llCheckResult.setVisibility(View.VISIBLE);
                        tvLinkBroken.setVisibility(View.GONE);
//                        LogUtil.d(ScanNumber);
                        cleanFace();
                        iosLoadDialog.show();
                        NetCheckResultOther(ScanNumber, "1", "");
                    } else {
                        ToastUtil.showToast("扫描结果为空，请重新扫描");
                        PlayAudioFile("扫描结果为空，请重新扫描");
                    }

                    break;

                case ReadOnceDone:
                    //身份证新中新 手持机  身份证
                    IDCard idCard = (IDCard) msg.obj;
                    if (idCard != null) {
                        // 如果在1分钟内刷相同的身份证，那么就不请求
                        timeNew = TimeUtil.getLocationTimeLong();
                        if (!checkIDAgain(idCard.getIDCardNo().trim())) {

                            llPrepare.setVisibility(View.GONE);
                            llCheckResult.setVisibility(View.VISIBLE);
                            tvLinkBroken.setVisibility(View.GONE);

                            cleanFace();
                            iosLoadDialog.show();
                            NetCheckResultOther(idCard.getIDCardNo().trim(), "2", idCard.getAddress().trim());
                        }
                    }


                    break;

            }
        }
    };
    private Message message;
    private Long mName;
    private String gateNo;
    private String ticketName;
    private String barcodeNo;
    private int str;
    private String certificateName;
    private String lastCheckTime;
    private String ticketName1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    // 读取身份证
    private void startReadThread() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();

    }

    // 返回 true  相同 小于  30 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 3) {
            System.out.println("zyf  未超过10秒 拒绝访问" + TimeUtil.getLocationTime());
//            PlayAudioFile("相同身份证30秒内拒绝二次检票");
            return true;
        } else {
            System.out.println("zyf  超过10秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }

    @Override
    protected void initView() {
        checkTip = (CheckTip) findViewById(R.id.check_result_tip);
        faceCheck = (RelativeLayout) findViewById(R.id.rl_fece_check);
        tvTime = (TextView) findViewById(R.id.tv_time);
        checkCount = (TextView) findViewById(R.id.tv_check_count);
        tvCheckingID = (TextView) findViewById(R.id.tv_checkid);

        //检票结果显示
        tickName = (CheckResultem) findViewById(R.id.cr_ticket_name);
//        tickNumber = (CheckResultem) findViewById(R.id.cr_ticket_number);
        tickPersonNum = (CheckResultem) findViewById(R.id.cr_ticket_person_number);
        tickPersonName = (CheckResultem) findViewById(R.id.cr_ticket_person_name);
        tickTime = (CheckResultem) findViewById(R.id.cr_ticket_time);
        tickMerction = (CheckResultem) findViewById(R.id.cr_ticket_merction);

        llCheckResult = (LinearLayout) findViewById(R.id.ll_check_result);
        llPrepare = (LinearLayout) findViewById(R.id.ll_prepare);
        tvLinkBroken = (TextView) findViewById(R.id.tv_link_broken);

        llPrepare.setVisibility(View.VISIBLE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.GONE);


        setting = (RelativeLayout) findViewById(R.id.rl_fece_setting);
        qrCheck = (RelativeLayout) findViewById(R.id.rl_qr);
        HqrCheck = (RelativeLayout) findViewById(R.id.rl_qr_Hong);
        idCheck = (RelativeLayout) findViewById(R.id.rl_id);
        idScanCheck = (RelativeLayout) findViewById(R.id.rl_scan_id);

        mCardCheck = (RelativeLayout) findViewById(R.id.rl_qr_card);
        if (jjhCheckTicketBean == null) {
            jjhCheckTicketBean = new JJHCheckTicketBean();
        }

        if (jjhCheckTicketOtherBean == null) {
            jjhCheckTicketOtherBean = new JJHCheckTicketOtherBean();
        }

        //获取TTS引擎
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(NewXinZhongXinActivity.this, new TTSListener());
        }

        // 身份证引入
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        //带nfc的机器需要关闭nfc才可以读身份证
        if (idCardReaderModule.hasNfc(this)) {
            idCardReaderModule.closeNFC();
        }

        // 二维码引入
        sm = new ScanDevice();
        sm.setOutScanMode(0);//启动就是广播模式

        //终端名称
        mName = (Long) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_MEATION, 0L);
        cleanFace();
        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, "请检票！");
        tvTime.setText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3));
        String locationTimeNew = TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3);
        String dataToday = locationTimeNew.substring(8, 10);
        //根据日期 对 统计数据清零
        String data = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_DATA, "");
        if (!dataToday.equals(data)) {
            //如果日期不相等 那么就清零
            SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
            //给日期保存 更新日期
            SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_DATA, dataToday);
        }
        checkCount.setText((Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0) + "");
        // 每隔1分钟就要去更新时间
        mHandler.sendEmptyMessageDelayed(faceUp, 10000);

        gateNo = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_GATENO, "");

    }

    @Override
    protected void initData() {

        faceCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llPrepare.setVisibility(View.GONE);
                llCheckResult.setVisibility(View.VISIBLE);
                tvLinkBroken.setVisibility(View.GONE);
                cleanFace();

            }
        });
        //二维码检票  扫
        qrCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayAudioFile("正在打开二维码扫描");
                qrCheck.setClickable(false);
                llPrepare.setVisibility(View.GONE);
                llCheckResult.setVisibility(View.VISIBLE);
                tvLinkBroken.setVisibility(View.GONE);
                cleanFace();
//                startActivityForResult(new Intent(NewXinZhongXinActivity.this, QrScanActivity.class), BaseConfig.QRBUNDLE);
                iosLoadDialog.dismiss();
            }
        });

        idCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIdRead();

            }
        });


        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewXinZhongXinActivity.this, SettingActivity.class));
            }
        });

        //新中新 特别引入
        //红外 引入
        HqrCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });

        mCardCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击卡类型 就要先去结束 身份证类型，以此反推

                llPrepare.setVisibility(View.GONE);
                llCheckResult.setVisibility(View.VISIBLE);
                tvLinkBroken.setVisibility(View.GONE);
                cleanFace();
                CloseReader();
                isReadingID = false;
                if (isReadingCard) {
                    PlayAudioFile("卡类型验票中，请勿重复点击");
                    return;
                }
                // 寻找卡类型
                OpenReader();
                PlayAudioFile("开始卡类型验票");
                isReadingCard = true;
                if (timer == null) {
                    timer = new Timer();
                }
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // (1) 使用handler发送消息
                        Message message = new Message();
                        message.what = cardAgain;
                        mHandler.sendMessage(message);
                    }
                }, 0, 5000);//每隔一秒使用handler发送一下消息,也就是每隔一秒执行一次,一直重复执行

            }
        });

    }

    public void startIdRead() {
        // 新中心 读取身份证 代码
        if (timer != null) {
            timer.cancel();
        }
        timer = null;
        cleanFace();
        //新中新 手持机 的读取身份证检票
        isReadingCard = false;
//        if (!isReadingID) {
//            PlayAudioFile("开始身份证验票");
            startReadThread();
//            isReadingID = true;
//        } else {
//            PlayAudioFile("身份证验票中，请勿重复点击");
//        }

    }

    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            if (!idCardReaderModule.isOpen()) {
                reading = false;
                idCardReaderModule.close();
                Log.e("ReadCardThread", "读卡器打开失败");
            }
            new UpdateTimerThread().start();

            while (reading) {
                try {
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
//                    if (!boolReadFringerprint)//是否需要读指纹
//                        retInfo = idCardReaderModule.getIDcardInfo();
//                    else
                    retInfo = idCardReaderModule.getIDcardInfo(false, false, false);

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                        //if(boolReadFringerprint)//仅测试时读取追加信息
                        //	retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
                        mHandler.obtainMessage(ReadOnceDone, retInfo.card).sendToTarget();
                        status = "";
                        Thread.sleep(500);
                    } else if (retInfo.errCode == IDCardReaderRetInfo.ERROR_RECV_FINDCARD) {
                        Log.e("ReadCardThread", "通信错误,重新打开读卡器");
                        idCardReaderModule.close();
                        Thread.sleep(3000);
                        idCardReaderModule.open();
                        if (!idCardReaderModule.isOpen()) {
                            reading = false;
                            idCardReaderModule.close();
                            Log.e("ReadCardThread", "读卡器打开失败");
                        }
                    } else {
                        status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                        mHandler.obtainMessage(ReadOnceDone, null).sendToTarget();
                        Thread.sleep(200);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead() {
            reading = false;
            interrupted();
        }

    }

    class UpdateTimerThread extends Thread {
        public void run() {
            while (reading) {
                mHandler.obtainMessage(UpDateTime).sendToTarget();
                util.sleep(1000);
            }
        }
    }

    @Override
    public int initLayoutId() {
        return R.layout.activity_new_xin_zhong_xin;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == BaseConfig.QROK) {
            if (requestCode == BaseConfig.QRBUNDLE) {
                qrCheck.setClickable(true);
                String QrString = (data.getStringExtra(BaseConfig.QRNUMBER)).trim();
                if (QrString != null && !QrString.equals("")) {
                    // 去做网络请求，请求数据
                    // 这个借口 是检票  金鸡湖项目
                    tvCheckingID.setVisibility(View.VISIBLE);
                    tvCheckingID.setText("票号：" + QrString);
                    NetCheckResult(QrString, "1");
                    // 这个借口是检票 日照馆等其他项目
//                    tvCheckingID.setVisibility(View.VISIBLE);
//                    tvCheckingID.setText("票号：" + QrString);
//                    NetCheckResultOther(QrString, "1");
                }
            }
        }

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SCAN_IDCARD_REQUEST:
                    idScanCheck.setClickable(true);
                    String result = data.getStringExtra("OCRResult");
                    try {
                        JSONObject jo = new JSONObject(result);
                        // 这个借口 是检票  金鸡湖项目
                        tvCheckingID.setVisibility(View.VISIBLE);
                        if (IDCardUtils.validateCard((String) jo.opt("num"))) {
                            tvCheckingID.setText("票号：" + (String) jo.opt("num"));
                            NetCheckResult((String) jo.opt("num"), "2");
                            // 这个借口是检票 日照馆等其他项目
//                    tvCheckingID.setVisibility(View.VISIBLE);
//                    tvCheckingID.setText("票号：" + QrString);
//                        NetCheckResultOther((String) jo.opt("num"), "2");
                        } else {
                            ToastUtil.showToast("身份证获取失败，请重试");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d("onResume");

        //进来就直接开始身份证
        startIdRead();

        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);
        sm.openScan();
        idScanCheck.setClickable(true);
        qrCheck.setClickable(true);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.d("onRestart");
        idScanCheck.setClickable(true);
        qrCheck.setClickable(true);
    }

    private void NetCheckResultOther(String qrString, String tyep, String address) {

        tvCheckingID.setText("票号：" + qrString);
        gateNo = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_GATENO, "");
        if (StringUtil.isNullOrEmpty(gateNo)) {
            iosLoadDialog.dismiss();
            ToastUtil.showToast("请先到设置进行绑定操作");
            PlayAudioFile("请先到设置进行绑定操作");
            return;
        }
        //判断检票 是否是 一票多客  还是 一票一客   默认 一票多客户
        int countNumber = (int) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_CHECKCOUNT, -1);

        jjhCheckTicketOtherBean.setCheckCount(countNumber);
        jjhCheckTicketOtherBean.setSearchDataType(tyep);
        jjhCheckTicketOtherBean.setSearchData(qrString);
        jjhCheckTicketOtherBean.setAddress(address);
        jjhCheckTicketOtherBean.setGateNo(gateNo);
        jjhCheckTicketOtherBean.setIsCollectionGate("N");
        jjhCheckTicketOtherBean.setSign("");
        jjhCheckTicketOtherBean.setTimestamp(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DAY_EN_ZYF));

        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).JJHCheckTicketOther(jjhCheckTicketOtherBean, new BaseSubscriber<JJHCheckResultOtherBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                checkTip.setVisibility(View.VISIBLE);
                iosLoadDialog.dismiss();
                showFacesError();
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(final JJHCheckResultOtherBean jjhCheckResultBean) {
                iosLoadDialog.dismiss();
                if (jjhCheckResultBean.getCode().equals("200")) {
                    tvCheckingID.setText("");
                    tvCheckingID.setVisibility(View.GONE);
                    checkTip.setVisibility(View.VISIBLE);
//                    请求成功 进行成功显示
                    showFacesSucessOhter(jjhCheckResultBean);
                    //  检票成功后才做统计
                    try {
                        vitalCountOther(jjhCheckResultBean);
                    } catch (Exception e) {
                    }

                } else if (jjhCheckResultBean.getCode().equals("100015")) {
                    // 进行弹框显示
                    SecondConfigDialog.getInstance().showDialog(NewXinZhongXinActivity.this, jjhCheckResultBean);
                    SecondConfigDialog.getInstance().setDialogClickListener(new SecondConfigDialog.DialogClickListener() {

                        @Override
                        public void ok() {
                            ToastUtil.showToast("点击了确定");
                            // 那么就去做二次确认的 操作
                            secondBean = new JJHCheckTicketOtherSecondBean();
                            secondBean.setCheckTicketType("1");
                            secondBean.setBarcodeNo(jjhCheckResultBean.getData().getBarcodeNo());
                            secondBean.setProjectId(Long.parseLong(jjhCheckResultBean.getData().getProjectId()));
                            secondBean.setGateNo(gateNo);
                            secondBean.setIsCollectionGate("N");
                            secondBean.setTimestamp(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DAY_EN_ZYF));
                            secondBean.setSign("");
                            secondClick(secondBean);
                        }

                        @Override
                        public void quxiao() {
                            ToastUtil.showToast("点击了取消");
                        }
                    });
                } else {
                    checkTip.setVisibility(View.VISIBLE);
                    showFacesAladyCheckOther(jjhCheckResultBean);
                }
            }
        });

    }

    private void secondClick(JJHCheckTicketOtherSecondBean secondBean) {

        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).ticketCheckerConfirmByCellPhone(secondBean, new BaseSubscriber<JJHCheckResultOtherBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                checkTip.setVisibility(View.VISIBLE);
                showFacesError();
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(JJHCheckResultOtherBean jjhCheckResultOtherBean) {
                if (jjhCheckResultOtherBean.getCode().equals("200")) {
                    tvCheckingID.setText("");
                    tvCheckingID.setVisibility(View.GONE);
                    checkTip.setVisibility(View.VISIBLE);
//                    请求成功 进行成功显示
                    showFacesSucessOhter(jjhCheckResultOtherBean);
                    //  检票成功后才做统计
                    try {
                        vitalCountOther(jjhCheckResultOtherBean);
                    } catch (Exception e) {
                    }
                } else {
                    checkTip.setVisibility(View.VISIBLE);
                    showFacesAladyCheckOther(jjhCheckResultOtherBean);
//                    ToastUtil.showToast(jjhCheckResultBean.getMessage());
                }
            }
        });
    }

    // 金鸡湖，检票 接口
    private void NetCheckResult(String qrString, String tyep) {
        if (StringUtil.isNullOrEmpty(gateNo)) {
            iosLoadDialog.dismiss();
            ToastUtil.showToast("请先到设置进行绑定操作");
            return;
        }

        //判断检票 是否是 一票多客  还是 一票一客   默认 一票多客户
        int countNumber = (int) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_CHECKCOUNT, -1);

        jjhCheckTicketBean.setCheckCount(countNumber);
        jjhCheckTicketBean.setSearchDataType(tyep);
        jjhCheckTicketBean.setSearchData(qrString);
        jjhCheckTicketBean.setGateNo(gateNo);
        jjhCheckTicketBean.setIsCollectionGate("N");
        jjhCheckTicketBean.setSign("");
        jjhCheckTicketBean.setTimestamp(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DAY_EN_ZYF));

        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).JJHCheckTicket(jjhCheckTicketBean, new BaseSubscriber<JJHCheckResultBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                checkTip.setVisibility(View.VISIBLE);
                showFacesError();
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(JJHCheckResultBean jjhCheckResultBean) {
                if (jjhCheckResultBean.getCode().equals("200")) {
                    checkTip.setVisibility(View.VISIBLE);
                    //请求成功 进行成功显示
                    showFacesSucess(jjhCheckResultBean);
                    // 检票成功后才做统计
                    vitalCount(jjhCheckResultBean);
                } else {
                    checkTip.setVisibility(View.VISIBLE);
                    showFacesAladyCheck(jjhCheckResultBean);
//                    ToastUtil.showToast(jjhCheckResultBean.getMessage());
                }
            }
        });
    }

    private void showFacesError() {
        checkTip.SetIcoBg(R.mipmap.error);
        checkTip.SetText(R.color.red_self, "未获取到数据");
        PlayAudioFile("未获取到数据，请检查网络");
        tickName.setVisibility(View.GONE);
//        tickNumber.setVisibility(View.GONE);
        tickPersonNum.setVisibility(View.GONE);
        tickPersonName.setVisibility(View.GONE);
        tickTime.setVisibility(View.GONE);
        tickMerction.setVisibility(View.GONE);

        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.GONE);
    }

    private void showFacesAladyCheck(JJHCheckResultBean jjhCheckResultBean) {
        if (jjhCheckResultBean.getMessage() != null) {
            PlayAudioFile(jjhCheckResultBean.getMessage() + "");
            checkTip.SetIcoBg(R.mipmap.tip);
            checkTip.SetText(R.color.yellow_title, jjhCheckResultBean.getMessage() + "");

            llPrepare.setVisibility(View.GONE);
            llCheckResult.setVisibility(View.GONE);
            tvLinkBroken.setVisibility(View.VISIBLE);

            String message = jjhCheckResultBean.getMessage();
//        message.replace("闸机", "终端");
            tvLinkBroken.setText(message);
            return;
        }
        if (jjhCheckResultBean.getData().getGateSoundName() != null) {
            gateSoundName = jjhCheckResultBean.getData().getGateSoundName();
            if (gateSoundName.equals("参数错误")) {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, "检票失败，参数错误");
                PlayAudioFile("检票失败，参数错误");
            } else if (StringUtil.isNullOrEmpty(gateSoundName)) {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, "检票失败，请重试");
                PlayAudioFile("检票失败，请重试");
            } else {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, gateSoundName);
                PlayAudioFile(gateSoundName);
            }
        } else {
            checkTip.SetIcoBg(R.mipmap.tip);
            checkTip.SetText(R.color.yellow_title, "检票失败，请重试");
            PlayAudioFile("检票失败，请重试");
        }

        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.VISIBLE);

        String message = jjhCheckResultBean.getMessage();
//        message.replace("闸机", "终端");
        tvLinkBroken.setText(message);
//        tickName.setVisibility(View.GONE);
//        tickNumber.setVisibility(View.GONE);
//        tickPersonNum.setVisibility(View.GONE);
//        tickPersonName.setVisibility(View.GONE);
//        tickTime.setVisibility(View.GONE);
//        tickMerction.setVisibility(View.GONE);
    }

    private void showFacesAladyCheckOther(JJHCheckResultOtherBean jjhCheckResultBean) {
//        if (jjhCheckResultBean.getMessage() != null) {
//            checkTip.SetIcoBg(R.mipmap.tip);
//            checkTip.SetText(R.color.yellow_title, jjhCheckResultBean.getMessage());
//            PlayAudioFile(jjhCheckResultBean.getMessage());
//
//            llPrepare.setVisibility(View.GONE);
//            llCheckResult.setVisibility(View.GONE);
//            tvLinkBroken.setVisibility(View.VISIBLE);
//
//            String message = jjhCheckResultBean.getMessage();
////        message.replace("闸机", "终端");
//            tvLinkBroken.setText(message);
//            return;
//        }
        if (jjhCheckResultBean.getData().getGateSoundName() != null) {
            gateSoundName = jjhCheckResultBean.getData().getGateSoundName();
            if (gateSoundName.equals("参数错误")) {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, "检票失败，参数错误");
                PlayAudioFile("检票失败，参数错误");
            } else if (StringUtil.isNullOrEmpty(gateSoundName)) {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, "检票失败，请重试");
                PlayAudioFile("检票失败，请重试");
            } else {
                checkTip.SetIcoBg(R.mipmap.tip);
                checkTip.SetText(R.color.yellow_title, gateSoundName);
                PlayAudioFile(gateSoundName);
            }
        } else {
            checkTip.SetIcoBg(R.mipmap.tip);
            checkTip.SetText(R.color.yellow_title, "检票失败，请重试");
        }

        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.VISIBLE);

        tvLinkBroken.setText(jjhCheckResultBean.getMessage());
//        tickName.setVisibility(View.GONE);
//        tickNumber.setVisibility(View.GONE);
//        tickPersonNum.setVisibility(View.GONE);
//        tickPersonName.setVisibility(View.GONE);
//        tickTime.setVisibility(View.GONE);
//        tickMerction.setVisibility(View.GONE);
    }

    private void vitalCount(JJHCheckResultBean jjhCheckResultBean) {
        int count = (Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
        count = count + jjhCheckResultBean.getData().getPassPersonSum();
        checkCount.setText(count + "");
        SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, count);
    }

    private void vitalCountOther(JJHCheckResultOtherBean jjhCheckResultBean) {
        int count = (Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
        count = count + jjhCheckResultBean.getData().getPassPersonSum();
        checkCount.setText(count + "");
        SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, count);
    }

    private void showFacesSucess(JJHCheckResultBean jjhCheckResultBean) {

        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.VISIBLE);
        tvLinkBroken.setVisibility(View.GONE);

        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, jjhCheckResultBean.getData().getGateSoundName());
        PlayAudioFile(jjhCheckResultBean.getData().getGateSoundName());

        tickName.setVisibility(View.VISIBLE);
//        tickNumber.setVisibility(View.VISIBLE);
        tickPersonNum.setVisibility(View.VISIBLE);
        tickPersonName.setVisibility(View.VISIBLE);
        tickTime.setVisibility(View.VISIBLE);
        tickMerction.setVisibility(View.VISIBLE);

        ticketName = jjhCheckResultBean.getData().getTicketName();
        if (!StringUtil.isNullOrEmpty(ticketName)) {
            tickName.setResultText(ticketName);
        }


        if (!StringUtil.isNullOrEmpty(str + "")) {
            tickPersonNum.setResultText(str + "");
        }

        if (jjhCheckResultBean.getData().getCertificateName() != null) {

            certificateName = jjhCheckResultBean.getData().getCertificateName();
            if (!StringUtil.isNullOrEmpty(certificateName)) {
                tickPersonName.setResultText(certificateName);
            }
        }

        lastCheckTime = jjhCheckResultBean.getData().getLastCheckTime();
        if (!StringUtil.isNullOrEmpty(lastCheckTime)) {
            tickTime.setResultText(lastCheckTime);
        }

        String mName = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_MEATION_NAME, "");
        if (!StringUtil.isNullOrEmpty(mName)) {
            tickMerction.setResultText(mName);
        }
    }

    private void showFacesSucessOhter(JJHCheckResultOtherBean jjhCheckResultBean) {

        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.VISIBLE);
        tvLinkBroken.setVisibility(View.GONE);

        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, jjhCheckResultBean.getData().getGateSoundName());
        PlayAudioFile(jjhCheckResultBean.getData().getGateSoundName());
        tickName.setVisibility(View.VISIBLE);
//        tickNumber.setVisibility(View.VISIBLE);
        tickPersonNum.setVisibility(View.VISIBLE);
        tickPersonName.setVisibility(View.VISIBLE);
        tickTime.setVisibility(View.VISIBLE);
        tickMerction.setVisibility(View.VISIBLE);

        ticketName = jjhCheckResultBean.getData().getTicketName();
        if (!StringUtil.isNullOrEmpty(ticketName)) {
            tickName.setResultText(ticketName);
        }
        // 门票数量
//        barcodeNo = jjhCheckResultBean.getData().getBarcodeNo();

//        restCheckCount = jjhCheckResultBean.getData().getRestCheckCount();
//        if (!StringUtil.isNullOrEmpty(str + "")) {
//            if (!StringUtil.isNullOrEmpty(restCheckCount + "")) {
//                tickNumber.setResultText(str + restCheckCount + "");
//            }
//        }
//        if (!StringUtil.isNullOrEmpty(barcodeNo)) {
//            tickNumber.setResultText(barcodeNo);
//        }

        str = jjhCheckResultBean.getData().getPassPersonSum();
        if (!StringUtil.isNullOrEmpty(str + "")) {
            tickPersonNum.setResultText(str + "");
        }

        certificateName = jjhCheckResultBean.getData().getCertificateName();
        if (!StringUtil.isNullOrEmpty(certificateName)) {
            tickPersonName.setResultText(certificateName);
        }

//        lastCheckTime = jjhCheckResultBean.getData().getLastCheckTime();
//        if (!StringUtil.isNullOrEmpty(lastCheckTime)) {
        tickTime.setResultText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN));
//        }

        String mName = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_MEATION_NAME, "");
        if (!StringUtil.isNullOrEmpty(mName)) {
            tickMerction.setResultText(mName);
        }
    }

    private void cleanFace() {

        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, "请检票");

        tickName.setResultText("");
        tickPersonNum.setResultText("");
        tickPersonName.setResultText("");
        tickTime.setResultText("");
        tickMerction.setResultText("");

        tickName.setVisibility(View.GONE);
//        tickNumber.setVisibility(View.GONE);
        tickPersonNum.setVisibility(View.GONE);
        tickPersonName.setVisibility(View.GONE);
        tickTime.setVisibility(View.GONE);
        tickMerction.setVisibility(View.GONE);
    }

    /*
     * 16进制大小端调整
     */
    public String ReserveHexStr(String Hex) {
        String ret = "";
        int begin = 0;
        int end = Hex.indexOf(",", begin);
        List list = new ArrayList();
        while (true) {
            if (-1 == end) {
                break;
            }
            String test = Hex.substring(begin, end);
            list.add(test);
            begin = end + 1;
            end = Hex.indexOf(",", begin);
        }

        for (int index = list.size() - 1; index >= 0; index--) {
            if (index < 0) {
                break;
            }
            String ltest = list.get(index).toString();
            ret += ltest;
        }

        return ret;
    }


    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器 身份证
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        stopRead();
        idCardReaderModule.close();
    }

    private void stopRead() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            try {
                ReadCardThreadhandler.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ReadCardThreadhandler = null;
        }
    }


    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i("zyf", "中文设置失败");
        } else {
            Log.i("zyf", "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            byte[] barocode = intent.getByteArrayExtra("barocode");
            int barocodelen = intent.getIntExtra("length", 0);
            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
            byte[] aimid = intent.getByteArrayExtra("aimid");
            barcodeStr = new String(barocode, 0, barocodelen);
            mHandler.obtainMessage(ReadScan, barcodeStr).sendToTarget();
            sm.stopScan();
        }
    };


    @Override
    protected void onStop() {
        super.onStop();
        //程序页面看不见后 ，就停止读取
        isReadingID = false;
        isReadingCard = false;
        if (timer != null) {
            timer.cancel();
        }
        timer = null;
        CloseReader();

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mScanReceiver);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isReadingID = false;
        isReadingCard = false;

        if (sm != null) {
            sm.stopScan();
            sm.setScanLaserMode(8);
            sm.closeScan();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtil.d("页面要被销毁了，请保存数据");
    }
}
